package com.example.temp;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256BarcodeValue {
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String barCode = "9908227045B2405070AB0057535";
        String value = "H4sIAAAAAAAAAKtWSkoscs5PSVWyUlCytDSwMDIyNzAxdTIyMTA1MDdwdDIwMDU3NTZV0uHiVMrJzMsGqeOMCnY2MA43MjE2NjQwsDAzUdJRKkktLgkuSSwqCcnMBRtmZAA0w8TQUsHQwMrI1MrQHKrINS8FlxJLoJKU1LLM5FS/RIgKf19foFhaYnJJflElTPDZ1pnPNs5/2rrmaf8OoGwB0FKQ8PMpW59tXPB89rTnu1ue7N4GkinKz0pNLoHpU3COdFJACANdW1JaDJIIA3kgPwkk6Jyfk18EEnu5e+KLzk1KtQCKWRuEIQEAAA==";

        String sha256 = sha256(barCode, value);
        System.out.println(sha256);
    }

    /**
     * sha256算法对barCode和value进行加密
     *
     * @param barCode 二维码
     * @param value 测试项json gzip压缩之后的字符串
     * @return @{@link String}
     */
    public static String sha256(String barCode, String value) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String sourceStr = barCode + value;

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] bt = sourceStr.getBytes("UTF-8");
        md.update(bt);
        String desStr = bytes2Hex(md.digest());

        return desStr;
    }

    private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
